package com.huatai.exchange.impl;

import com.faneui.common.bean.AbstractLogger;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.Constants;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ListUtils;
import com.faneui.dal.DBUtils;
import com.huatai.exchange.conn.LocalConnection;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.huatai.exchange.dal.model.ExcFileLoadRecord;
import com.huatai.exchange.integration.base.service.FileOperateService;
import com.huatai.exchange.service.ClearHisDataService;
import com.huatai.exchange.service.ExcFileLoadInfoService;
import com.huatai.exchange.service.ExcFileLoadRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ClearHisDataServiceImpl extends AbstractLogger implements ClearHisDataService {


    @Autowired
    private ExcFileLoadRecordService excFileLoadRecordService;

    @Autowired
    private ExcFileLoadInfoService excFileLoadInfoService;

    @Autowired
    private FileOperateService fileOperateService;

    @Autowired
    private LocalConnection localConnection;


    @Override
    public void clearHisDataRecord() throws BusinessException {
        ExcFileLoadInfo param = new ExcFileLoadInfo();
        param.setStatus(Constants.boolean_true);
        List<ExcFileLoadInfo> excFileLoadInfos = excFileLoadInfoService.queryExcFileLoadInfoList(param);
        for (ExcFileLoadInfo excFileLoadInfo : excFileLoadInfos) {
            Integer keepDays = excFileLoadInfo.getKeepDays();
            if (keepDays == null || -1 == keepDays) {
                continue;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, -keepDays);
            String occurDate = DateFormatUtils.yyyyMMdd.format(calendar.getTime());
            ExcFileLoadRecord param1 = new ExcFileLoadRecord();
            param1.setLastDate(occurDate);
            param1.setLoadId(excFileLoadInfo.getId());
            List<ExcFileLoadRecord> excFileLoadRecords = excFileLoadRecordService.queryExcFileLoadRecordList(param1);
            if (ListUtils.isNotEmpty(excFileLoadRecords))
                for (ExcFileLoadRecord record : excFileLoadRecords) {
                    clearHisDataRecord(record, excFileLoadInfo.getTableName());
                    logger.info("已清除备份数据或文件[" + excFileLoadInfo.getFileName() + "]日期[" + record.getLastDate() + "]历史数据");
                }
            logger.info("已清除备份数据或文件[" + excFileLoadInfo.getFileName() + "]前[" + keepDays + "]天历史数据");

        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void clearHisDataRecord(String recordId) throws BusinessException {
        ExcFileLoadRecord record = excFileLoadRecordService.queryExcFileLoadRecord(recordId);
        if (record == null)
            throw new BusinessException("");
        String loadId = record.getLoadId();
        ExcFileLoadInfo info = excFileLoadInfoService.queryExcFileLoadInfo(loadId);
        clearHisDataRecord(record, info.getTableName());
    }

    @Transactional(rollbackFor = Exception.class)
    public void clearHisDataRecord(ExcFileLoadRecord record, String tableName) throws BusinessException {
        // 删除文件
        String filePath = record.getFilePath();
        String occurDate = record.getOccurDate();
        // 3,删除远程文件
        if (StringUtils.isNotBlank(filePath)) {
            try {
                fileOperateService.deleteFile(filePath);
            } catch (Exception ex) {
                logger.error("文件不存在，不影响数据删除操作", ex);
            }
        }
        // 2,删除数据表
        if (StringUtils.isNotBlank(tableName)) {
            deleteData(tableName, occurDate);
        }
        // 1,删除记录
        excFileLoadRecordService.deleteExcFileLoadRecord(record.getId());
    }

    public void deleteData(String tableName, String occurDate) throws BusinessException {
        try {
            String sql = " delete " + tableName + " where occur_date = ? ";
            DBUtils.execute(localConnection.getConn(), sql, occurDate);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }
}
